package by.grsu.shedule.api;

import java.util.Random;

import android.content.Context;
import android.preference.PreferenceManager;
import android.util.Log;
import by.grsu.shedule.constants.ApplicationConstants;
import by.grsu.shedule.constants.Week;
import by.grsu.shedule.fragment.DateFragment;
import by.grsu.shedule.util.CalendarHelper;

public class SheduleAPI {

	private static final String TAG = SheduleAPI.class.getSimpleName();

	private static SheduleAPI instance;

	private static Context mContext;

	private static String resultUrl;

	private SheduleAPI(Context context) {
		mContext = context;
	}

	public static SheduleAPI newInstance(Context context) {
		if (instance == null) {
			instance = new SheduleAPI(context);
		}
		return instance;
	}

	private static String generateUrl(Week week) {
		int cource = getCurrentCourse();
		int group = getCurrentGroup();
		if (cource == 0 || group == 0) {
			return null;
		} else {
			long l = System.currentTimeMillis();
			Random rnd = new Random(l);
			String xmlurl;
			if (week == Week.THIS) {
				xmlurl = "xmls_this_week.php?";
			} else {
				xmlurl = "xmls_next_week.php?";
			}
			long num1 = l % 137L;
			long num2 = l % 9913L;
			int num3 = Math.abs(rnd.nextInt() % 100);
			int num4 = Math.abs(rnd.nextInt() % 100);
			String r = "" + num3 + "" + (num1 + num2) + "" + num4;

			return "http://news.mf.grsu.by/~mobile/" + xmlurl + "kurs="
					+ cource + "&group=" + group + "&ms=" + l + "&diff=" + r;
		}

	}


	public static String getUrl() {
		if (resultUrl == null) {
			resultUrl = generateUrl(Week.THIS);
		}

		return resultUrl;
	}

	public static void refreshUrl() {
		resultUrl = generateUrl(CalendarHelper.getWeek(DateFragment
				.getCurrentWeek()));
	}
	
	public static int getCurrentGroup(){
		try {
			return Integer.valueOf(PreferenceManager
					.getDefaultSharedPreferences(mContext)
					.getString(ApplicationConstants.GROUP_PREFERENCES, "0")
					.trim());
		} catch (NumberFormatException e) {
			Log.e(TAG, "error when get group from preferences");
		}
		return 0;
	}
	
	public static int getCurrentCourse(){
		try {
			return Integer.valueOf(PreferenceManager
					.getDefaultSharedPreferences(mContext)
					.getString(ApplicationConstants.COURSE_PREFERENCES, "0")
					.trim());
		} catch (NumberFormatException e) {
			Log.e(TAG, "error when get course from preferences", e);
		}

		return 0;
	}
	
}
